<template>
    <s-clean-layout :navbar="normal" title="联系人详情">
    <!-- 顶部个人信息 -->
    <view class="profile">
      <view class="avatar" v-if="contactInfo.img">
        <image class="avatar-img" :src="contactInfo.img" mode="aspectFill" @error="handleImageError"></image>
      </view>
      <view class="avatar" v-else>
        <view class="avatar-placeholder">{{ getNameInitial(contactInfo.name) }}</view>
      </view>
      <view class="nickname">{{ contactInfo.name }}</view>
      <view class="tags">
        <view class="tag" @tap="onEditContact" :style="{ background: '#4CAF50' }">
          <uni-icons type="compose" size="20" color="#fff"></uni-icons>
        </view>
        <view class="tag" @tap="onDeleteContact" :style="{ background: '#FF5252' }">
          <uni-icons type="trash" size="20" color="#fff"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 标签页导航 -->
    <view class="tabs">
      <view class="tab-item" v-for="(tab, index) in tabs" :key="index" :class="{ active: currentTab === index }" @tap="switchTab(index)">
        {{ tab.name }}
      </view>
    </view>

    <!-- 标签页内容 -->
    <view class="tab-content">
      <!-- 资料标签页 -->
      <profile-tab 
        v-if="currentTab === 0" 
        :profileData="profileData"
        :hobbies="hobbies"
        :dislikes="dislikes"
        :skills="skills"
        :tastes="tastes"
        :habits="habits"
        :contactDetail="contactDetail"
        :contactId="contactInfo.id"
        @refresh="refreshContactInfo"
        @longpress="handleLongPress"
      />

      <!-- 纪念日标签页 -->
      <memorial-tab 
        v-if="currentTab === 1" 
        ref="memorialTabRef"
        :memorialData="memorialData"
        :contactId="contactInfo.id"
        :contactName="contactInfo.name"
        :contactAvatar="contactInfo.img"
        :currentTab="currentTab"
        :tabIndex="1"
        @refresh="onTabRefresh"
        @longpress="handleLongPress"
      />

      <!-- 事件标签页 -->
      <event-tab 
        v-if="currentTab === 2" 
        ref="eventTabRef"
        :events="events"
        :contactId="contactInfo.id"
        :currentTab="currentTab"
        :tabIndex="2"
        @refresh="onTabRefresh"
        @longpress="handleLongPress"
      />

      <!-- 记账标签页 -->
      <accounting-tab 
        v-if="currentTab === 3" 
        ref="accountingTabRef"
        :accountingData="accountingData"
        :contactId="contactInfo.id"
        :currentTab="currentTab"
        :tabIndex="3"
        @refresh="onTabRefresh"
        @longpress="handleLongPress"
      />

      <!-- 更多标签页 -->
      <more-tab 
        v-if="currentTab === 4" 
        ref="moreTabRef"
        :moreData="moreData"
        :contactId="contactInfo.id"
        :currentTab="currentTab"
        :tabIndex="4"
        @refresh="onTabRefresh"
        @longpress="handleLongPress"
      />
    </view>

    <!-- 悬浮按钮 - 在资料、纪念、事件、记账、更多 tab 下显示 -->
    <view class="fab-button" @tap="onAddItem" v-if="currentTab >= 0 && currentTab <= 4">
      <uni-icons type="plusempty" size="24" color="#FFFFFF" />
    </view>
  </s-clean-layout>
</template>

<script setup>
// 在 import 部分添加所有需要的 API
import { ref, onMounted, computed, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import ProfileTab from './components/ProfileTab.vue'
import MemorialTab from './components/MemorialTab.vue'
import EventTab from './components/EventTab.vue'
import AccountingTab from './components/AccountingTab.vue'
import MoreTab from './components/MoreTab.vue'
import ContactApi from '@/sheep/api/contact/contact';
import ImportDayApi from '@/pages/contact/api/importday';
import EventApi from '@/pages/contact/api/event';
import TransactionApi from '@/sheep/api/money/transaction';
import UserArticleApi from '@/sheep/api/article/user_article';

// 标签页配置
const tabs = [
  { name: '资料' },
  { name: '纪念' },
  { name: '事件' },
  { name: '记账' },
  { name: '更多' }
]

// 当前选中的标签页
const currentTab = ref(0)

// 联系人信息
const contactInfo = ref({
  id: '',
  name: '',
  img: ''
})

// 联系人详细资料
const contactDetail = ref({})

// 添加子组件引用
const memorialTabRef = ref(null)
const eventTabRef = ref(null)
const accountingTabRef = ref(null)
const moreTabRef = ref(null)

// 处理图片加载错误
const handleImageError = () => {
  contactInfo.value.img = ''
}

// 获取姓名首字母作为头像占位符
const getNameInitial = (name) => {
  if (!name) return '?'
  return name.charAt(0).toUpperCase()
}

// 从联系人详情中提取基本资料
const profileData = computed(() => {
  const detail = contactDetail.value
  const data = {}
  
  if (detail.homeAddress) data['现居城市'] = detail.homeAddress
  if (detail.relationshipName) data['与我的关系'] = detail.relationshipName
  if (detail.birthday) data['生日'] = formatBirthday(detail.birthday)
  
  return data
})

// 格式化生日日期
const formatBirthday = (birthday) => {
  if (!birthday) return ''
  
  // 如果是时间戳格式，转换为日期字符串
  if (typeof birthday === 'number') {
    const date = new Date(birthday)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
  
  // 如果已经是日期字符串格式，直接返回
  return birthday
}

// 从联系人详情中提取标签数据（包含颜色信息）
const hobbies = computed(() => {
  if (!contactDetail.value.contactTagInfos || !contactDetail.value.contactTagInfos.LIKE) return []
  return contactDetail.value.contactTagInfos.LIKE.map(tag => ({
    tagName: tag.tagName,
    color: tag.color || '#FF6B6B'
  }))
})

const dislikes = computed(() => {
  if (!contactDetail.value.contactTagInfos || !contactDetail.value.contactTagInfos.NOTLIKE) return []
  return contactDetail.value.contactTagInfos.NOTLIKE.map(tag => ({
    tagName: tag.tagName,
    color: tag.color || '#FF5252'
  }))
})

const skills = computed(() => {
  if (!contactDetail.value.contactTagInfos || !contactDetail.value.contactTagInfos.SKILL) return []
  return contactDetail.value.contactTagInfos.SKILL.map(tag => ({
    tagName: tag.tagName,
    color: tag.color || '#4CAF50'
  }))
})

// 添加口味和习惯的计算属性
const tastes = computed(() => {
  if (!contactDetail.value.contactTagInfos || !contactDetail.value.contactTagInfos.EAT) return []
  return contactDetail.value.contactTagInfos.EAT.map(tag => ({
    tagName: tag.tagName,
    color: tag.color || '#FF9800'
  }))
})

const habits = computed(() => {
  if (!contactDetail.value.contactTagInfos || !contactDetail.value.contactTagInfos.HABIT) return []
  return contactDetail.value.contactTagInfos.HABIT.map(tag => ({
    tagName: tag.tagName,
    color: tag.color || '#9C27B0'
  }))
})

// 其他数据保持不变
const memorialData = ref([]);
const events = ref([]);
const accountingData = ref([]);
const moreData = ref([]);

// 切换标签页
const switchTab = (index) => {
  currentTab.value = index;
  
  // 更新全局状态
  const app = getApp();
  if (app && app.globalData) {
    app.globalData.currentTab = index;
  }
  
  // 延迟加载对应tab的数据
  setTimeout(() => {
    loadTabData(index);
  }, 100);
};

// 加载指定tab的数据
const loadTabData = (tabIndex) => {
  if (!contactInfo.value.id) return;
  
  switch (tabIndex) {
    case 1: // 纪念日
      if (memorialTabRef.value && memorialTabRef.value.loadMemorialData) {
        memorialTabRef.value.loadMemorialData();
      }
      break;
    case 2: // 事件
      if (eventTabRef.value && eventTabRef.value.loadEvents) {
        eventTabRef.value.loadEvents();
      }
      break;
    case 3: // 记账
      if (accountingTabRef.value && accountingTabRef.value.loadAccountingData) {
        accountingTabRef.value.loadAccountingData();
      }
      break;
    case 4: // 更多
      if (moreTabRef.value && moreTabRef.value.queryArticleList) {
        moreTabRef.value.queryArticleList();
      }
      break;
    default:
      break;
  }
};

// 获取联系人信息
const getContactInfo = async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const id = currentPage.options.id;
  const tab = currentPage.options.tab; // 获取tab参数
  
  if (!id) return;
  
  contactInfo.value.id = id;
  
  // 如果指定了tab，切换到对应的标签页
  if (tab) {
    currentTab.value = Number(tab);
  }
  
  // 初始化全局状态
  const app = getApp();
  if (app && app.globalData) {
    app.globalData.currentTab = currentTab.value;
  }
  
  await refreshContactInfo();
  
  // 加载当前tab的数据
  loadTabData(currentTab.value);
};

// 刷新联系人信息的方法，可以在多处调用
const refreshContactInfo = async () => {
  if (!contactInfo.value.id) return;
  
  try {
    // 调用API获取联系人详细信息
    const res = await ContactApi.queryContactDetail({ id: contactInfo.value.id });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      // 更新联系人基本信息
      contactInfo.value.name = res.data.name || '';
      contactInfo.value.img = res.data.avatarUrl || '';
      
      // 保存完整的联系人详情数据
      contactDetail.value = res.data;
    } else {
      uni.showToast({
        title: '获取联系人信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取联系人详情失败', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 处理子组件刷新完成事件
const onTabRefresh = () => {
  console.log('子组件数据刷新完成');
  // 可以在这里处理一些全局状态更新
};

// 添加项目
const onAddItem = () => {
  const tabName = tabs[currentTab.value].name
  
  // 根据当前标签页执行不同的操作
  if (tabName === '事件') {
    // 跳转到事件添加页面，添加联系人名称和头像参数
    uni.navigateTo({
      url: `/pages/contact/event-edit?contactId=${contactInfo.value.id}&mode=add&contactName=${encodeURIComponent(contactInfo.value.name)}&contactImg=${encodeURIComponent(contactInfo.value.img || '')}`
    });
  } else if (tabName === '纪念') {
    // 跳转到纪念日添加页面，添加联系人名称和头像参数
    uni.navigateTo({
      url: `/pages/contact/memorial-edit?contactId=${contactInfo.value.id}&mode=add&contactName=${encodeURIComponent(contactInfo.value.name)}&contactImg=${encodeURIComponent(contactInfo.value.img || '')}`
    })
  } else if (tabName === '记账') {
    // 跳转到记账添加页面
    uni.navigateTo({
      url: `/pages/contact/accounting-edit?contactId=${contactInfo.value.id}&mode=add`
    })
  } else if (tabName === '更多') {
    // 跳转到笔记添加页面
    uni.navigateTo({
      url: `/pages/contact/note-edit?contactId=${contactInfo.value.id}&mode=add`
    })
  } else {
    // 其他标签页的处理（暂时保留原来的逻辑）
    uni.navigateTo({
      url: `/pages/contact/edit?type=${tabName}&contactId=${contactInfo.value.id}`
    })
  }
}

// 监听currentTab变化
watch(currentTab, (newTab, oldTab) => {
  console.log('Tab切换:', oldTab, '->', newTab);
  // 更新全局状态
  const app = getApp();
  if (app && app.globalData) {
    app.globalData.currentTab = newTab;
  }
});

onMounted(() => {
  console.log('联系人详情页 onMounted');
  getContactInfo()
})

// 添加页面显示时的处理
onShow(() => {
  console.log('联系人详情页 onShow - currentTab:', currentTab.value);
  
  // 确保全局状态同步
  const app = getApp();
  if (app && app.globalData) {
    app.globalData.currentTab = currentTab.value;
  }
  
  // 如果已经有联系人ID，重新加载当前tab数据
  if (contactInfo.value.id) {
    loadTabData(currentTab.value);
  }
});

// 编辑联系人
const onEditContact = () => {
  uni.navigateTo({
    url: `/pages/contact/edit?id=${contactInfo.value.id}`
  });
}

// 删除联系人
const onDeleteContact = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该联系人吗？',
    success: function (res) {
      if (res.confirm) {
        deleteContact();
      }
    }
  });
}

// 删除联系人
const deleteContact = async () => {
  try {
    uni.showLoading({
      title: '删除中...'
    });
    
    const res = await ContactApi.deleteContact({
      id: contactInfo.value.id
    });
    
    if (res.code === 0) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || '删除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('删除联系人失败', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 添加长按处理函数
const handleLongPress = (item, type) => {
  // 根据不同类型显示不同的操作菜单
  uni.showActionSheet({
    itemList: ['编辑', '删除'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 编辑操作
        navigateToEdit(item, type);
      } else if (res.tapIndex === 1) {
        // 删除操作
        showDeleteConfirm(item, type);
      }
    }
  });
};

// 导航到编辑页面
const navigateToEdit = (item, type) => {
  switch (type) {
    case 'memorial':
      uni.navigateTo({
        url: `/pages/contact/memorial-edit?id=${item.id}&contactId=${contactInfo.value.id}&mode=edit`
      });
      break;
    case 'event':
      uni.navigateTo({
        url: `/pages/contact/event-edit?id=${item.id}&contactId=${contactInfo.value.id}&mode=edit`
      });
      break;
    case 'accounting':
      uni.navigateTo({
        url: `/pages/contact/accounting-edit?id=${item.id}&contactId=${contactInfo.value.id}&mode=edit`
      });
      break;
    case 'more':
      uni.navigateTo({
        url: `/pages/contact/note-edit?id=${item.id}&contactId=${contactInfo.value.id}&mode=edit`
      });
      break;
    default:
      break;
  }
};

// 显示删除确认对话框
const showDeleteConfirm = (item, type) => {
  let confirmText = '确定要删除这条记录吗？';
  
  uni.showModal({
    title: '提示',
    content: confirmText,
    success: (res) => {
      if (res.confirm) {
        deleteItem(item, type);
      }
    }
  });
};

// 删除项目
const deleteItem = async (item, type) => {
  try {
    uni.showLoading({
      title: '删除中...'
    });
    
    let result;
    
    // 根据不同类型调用不同的删除接口
    switch (type) {
      case 'memorial':
        result = await ImportDayApi.deleteImportDay({
          id: item.id,
          contactId: contactInfo.value.id
        });
        break;
      case 'event':
        result = await EventApi.deleteContactEvent({
          id: item.id,
          contactId: contactInfo.value.id
        });
        break;
      case 'accounting':
        result = await TransactionApi.deleteHumanTransaction({
          id: item.id,
          contactId: contactInfo.value.id
        });
        break;
      case 'more':
        result = await UserArticleApi.deleteArticle({
          id: item.id,
          contactId: contactInfo.value.id
        });
        break;
      default:
        uni.hideLoading();
        return;
    }
    
    uni.hideLoading();
    
    if (result && result.code === 0) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
      // 刷新对应标签页的数据
      refreshTabData(type);
    } else {
      uni.showToast({
        title: result?.msg || '删除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('删除失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 刷新标签页数据
const refreshTabData = (type) => {
  switch (type) {
    case 'memorial':
      // 刷新纪念日数据
      if (currentTab.value === 1) {
        loadTabData(1);
      }
      break;
    case 'event':
      // 刷新事件数据
      if (currentTab.value === 2) {
        loadTabData(2);
      }
      break;
    case 'accounting':
      // 刷新记账数据
      if (currentTab.value === 3) {
        loadTabData(3);
      }
      break;
    case 'more':
      // 刷新更多数据
      if (currentTab.value === 4) {
        loadTabData(4);
      }
      break;
    default:
      break;
  }
};
</script>

<style lang="scss" scoped>
.profile {
  padding: 48rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #B388FF;
  color: #fff;
  font-size: 60rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nickname {
  margin-top: 24rpx;
  font-size: 16px;
  color: #333;
}

.tags {
  margin-top: 24rpx;
  display: flex;
  gap: 24rpx;
}

.tag {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tabs {
  margin-top: 24rpx;
  height: 88rpx;
  display: flex;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #2196F3;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 48rpx;
  height: 4rpx;
  background: #2196F3;
  border-radius: 2rpx;
}

.tab-content {
  flex: 1;
  overflow: auto;
}

.fab-button {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #1976d2;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  z-index: 20;
}

/* Add menu styles inside the style block */
.menu-popup {
  background-color: #fff;
  border-radius: 12px 12px 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.menu-text {
  margin-left: 10px;
  font-size: 16px;
  color: #333;
}

.delete-text {
  color: #FF3B30;
}

.menu-cancel {
  text-align: center;
  padding: 20px;
  font-size: 16px;
  color: #007AFF;
}
</style>
